package com.sillyhat.project.test.activiti;

import com.sillyhat.project.utils.JunitTestSupport;

import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * HelloActiviti
 *
 * @author 徐士宽
 * @date 2017/5/10 9:53
 */
public class HelloActiviti extends JunitTestSupport {

    private Logger logger = LoggerFactory.getLogger(HelloActiviti.class);

    @Autowired
    private ProcessEngine processEngine;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private TaskService taskService;

    /**
     * Activiti测试
     */
    @Test
    public void checkActiviti(){
        String activitiName = processEngine.getName();
        String version = processEngine.VERSION;
        logger.info("当前名称:{},版本号:{}",activitiName,version);
    }

    /**
     * 流程部署
     */
    @Test
    public void deploymentProcess(){
        String processPath = "E:\\temp\\file\\AskForLeave.bpmn";
        File file = new File(processPath);
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            //部署文件
            Deployment deployment = repositoryService.createDeployment().addInputStream(file.getName(),is).deploy();
            logger.info("部署成功，部署ID为：{}",deployment.getId());
        } catch (FileNotFoundException e) {
            logger.error("获取流程文件发生异常",e);
        }
    }

    /**
     * 流程查询
     */
    @Test
    public void queryProcess(){
        String processId = "1";
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(processId).singleResult();
        logger.info("流程名称：{},流程ID:{}",processDefinition.getName(),processDefinition.getId());
    }


    /**
     * 启动流程
     */
    @Test
    public void startProcess(){
        String processKey = "AskForLeave";//流程图的流程ID
        logger.info("启动流程");

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processKey);
        logger.info("流程启动成功->name:{}  id:{}   DeploymentId:{}",processInstance.getName(),processInstance.getId(),processInstance.getDeploymentId());
    }

    /**
     * 签收
     */
    @Test
    public void signoffProcess(){
//        String processId = "2501";//流程图的流程ID
        String processId = "10001";//流程图的流程ID
        //根据流程ID获取当前任务：
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processId).list();
//        List<Task> taskList = processEngine.getTaskService() // 任务相关Service
//                .createTaskQuery() // 创建任务查询
//                .taskAssignee("李四") // 指定某个人
//                .list();
        for (Task task : tasks){
            logger.info("任务ID:{}",task.getId());
            logger.info("任务名称:{}",task.getName());
            logger.info("任务创建时间:{}",task.getCreateTime());
            logger.info("任务委派人:{}",task.getAssignee());
            logger.info("流程实例ID:{}",task.getProcessInstanceId());
            //认领任务
            taskService.claim(task.getId(), "xushikuan");
            logger.info("签收完成");
        }
    }


    /**
     * 审批通过
     */
    @Test
    public void finishProcess(){
//        String processId = "2501";//流程图的流程ID
        String processId = "10001";//流程图的流程ID
        //根据流程ID获取当前任务：
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processId).list();
        for (Task task : tasks){
            logger.info("任务ID:{}",task.getId());
            logger.info("任务名称:{}",task.getName());
            logger.info("任务创建时间:{}",task.getCreateTime());
            logger.info("任务委派人:{}",task.getAssignee());
            logger.info("流程实例ID:{}",task.getProcessInstanceId());
            Map<String, Object> variables = new HashMap<String,Object>();
            //传入流程变量决定流程走向
            //${days<=1}
            //${days>1 && days <=3}
            //${days>3}
//            variables.put("days", "5");
            variables.put("days", "2");
            //完成任务
            taskService.complete(task.getId(),variables);
//            taskService.complete(task.getId());
            logger.info("审批完成");
        }
    }

    /**
     * 查询当前流程节点
     */
    @Test
    public void getCurrentProcess(){
        String processId = "2501";//流程图的流程ID
        // 核实流程是否结束
		HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processId).singleResult();
		logger.info("Process instance end time: {}",historicProcessInstance.getEndTime());
        //根据流程ID获取当前任务：
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processId).list();
        for (Task task : tasks){
            logger.info("任务ID:{}",task.getId());
            logger.info("任务名称:{}",task.getName());
            logger.info("任务创建时间:{}",task.getCreateTime());
            logger.info("任务委派人:{}",task.getAssignee());
            logger.info("流程实例ID:{}",task.getProcessInstanceId());
        }
        logger.info("-------------------------------");
        processId = "10001";//流程图的流程ID
        // 核实流程是否结束
        historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processId).singleResult();
        logger.info("Process instance end time: {}",historicProcessInstance.getEndTime());
        //根据流程ID获取当前任务：
        tasks = taskService.createTaskQuery().processInstanceId(processId).list();
        for (Task task : tasks){
            logger.info("任务ID:{}",task.getId());
            logger.info("任务名称:{}",task.getName());
            logger.info("任务创建时间:{}",task.getCreateTime());
            logger.info("任务委派人:{}",task.getAssignee());
            logger.info("流程实例ID:{}",task.getProcessInstanceId());
        }
    }
}
